<?php

define('SEDIR', __DIR__);

class SE {
    public static $config=null, $app=null;
    
    public static $service, $output;
    
    private static $stime;
    
    public static function startApp () {
        if(self::$config == null) throw new SEException('Application config must be specified.');
        
        self::preload();
        
        self::$stime  = microtime(true);
        self::$output = '';
        self::resolveUrl();
        
        self::$app = new SE::$service['id'];
        self::$app->execute();
    }
    
    private static function preload () {
        if(!is_dir(APP_DIR.'/preload')) return false;
        
        foreach(glob(APP_DIR.'/preload/*.php') as $file) {
            require_once $file;
        }
    }
    
    public static function resolveUrl () {
        $http = $_SERVER['HTTPS']? 'https://': 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $request = $http.$host.$_SERVER['REQUEST_URI'];
        $conf = self::$config['app']['baseUrl'].(strstr($request, self::$config['app']['scriptName'])? self::$config['app']['scriptName']: '');
        $request = trim(str_replace($conf, '', $request), '/');
        
        $p = explode('?', $request);
        $tservice = $p[0];
        $params  = $p[1];
        
        if($params !== null) parse_str($params, $_GET);
        
        $service = strstr($tservice, '.', true)? strstr($tservice, '.', true): $tservice;
        $action = strstr($tservice, '.')? str_replace('.', '', strstr($tservice, '.')): 'main';
        
        self::$service = empty($request)?
                         array('id'=>'mainService','action'=>'mainAction'):
                         array('id'=>$service.'Service','action'=>$action.'Action');
    }
    
    public static function addToResponse ($str, $before=false) {
        self::$output = $before? $str.self::$output: self::$output.$str;
    }
    
    public static function addHeader ($str) {
        header($str);
    }
    
    public static function autoload ($class) {
        if(strstr($class, 'Service')) $path = '/services';
        elseif(strstr($class, 'Module')) $path = '/modules';
        elseif(strstr($class, 'Component')) $path = '/components';
        else $path = '/modules';
        
        if(is_file(APP_DIR.$path.'/'.$class.'.php')) require APP_DIR.$path.'/'.$class.'.php';
        elseif(is_file(SEDIR.$path.'/'.$class.'.php')) require SEDIR.$path.'/'.$class.'.php';
        else throw new SEException('Class "'.$class.'" not found.');
    }
    
    public static function getExecTime () {
        return microtime(true) - self::$stime;
    }
}

class SEException extends Exception {}

spl_autoload_register('SE::autoload');

require_once 'service.php';
require_once 'component.php';